// 状态管理入口文件
// 统一导出所有stores和相关工具

// 核心stores
export { useGlobalStore, useAppState, useSettings, useModuleStates, useNotifications, usePerformanceMetrics, useGlobalActions } from './globalStore';
export { useTabStore } from './tabStore';
export { useRouterStore } from './routerStore';

// Store工厂和工具
export { 
  createStore, 
  createSimpleStore, 
  createReadonlyStore,
  combineStores,
  createSelector,
  subscribeToStore,
  debugStore,
  analyzeStorePerformance,
  healthCheckStore,
  createBaseState,
  createBaseActions,
  persistenceManager
} from './storeFactory';

// 中间件
export { crossModuleSync, useAutoSync } from './middleware/crossModuleSync';
export { performanceMonitor, usePerformanceMonitoring } from './middleware/performanceMonitor';
export { persistenceManager as persistence } from './middleware/persistenceManager';

// 类型定义
export type { 
  StoreConfig, 
  BaseStoreState, 
  BaseStoreActions, 
  BaseStore 
} from './storeFactory';

export type {
  GlobalSettings,
  AppState,
  ModuleStates,
  Notification,
  GlobalState,
  GlobalActions,
  GlobalStore,
  AppTheme,
  AppLanguage
} from './globalStore';

export type {
  Tab,
  TabStatus,
  TabGroup,
  TabHistory,
  TabConfig,
  TabState,
  TabActions,
  TabStore
} from './tabStore';

export type {
  ViewType,
  RouterState,
  RouterActions,
  RouterStore
} from './routerStore';

export type {
  CrossModuleEvent,
  EventListener
} from './middleware/crossModuleSync';

export type {
  PerformanceMetrics,
  SlowUpdate,
  HotPath
} from './middleware/performanceMonitor';

export type {
  PersistenceConfig
} from './middleware/persistenceManager';

// 初始化函数
export const initializeStores = async () => {
  console.log('🏪 Initializing stores...');
  
  try {
    // 初始化全局store
    const globalStore = useGlobalStore.getState();
    await globalStore.initialize();
    
    // 初始化其他stores
    const tabStore = useTabStore.getState();
    if (tabStore.initialize) {
      await tabStore.initialize();
    }
    
    const routerStore = useRouterStore.getState();
    if (routerStore.initialize) {
      await routerStore.initialize();
    }
    
    console.log('✅ All stores initialized successfully');
  } catch (error) {
    console.error('❌ Failed to initialize stores:', error);
    throw error;
  }
};

// 清理函数
export const cleanupStores = () => {
  console.log('🧹 Cleaning up stores...');
  
  try {
    // 重置所有stores
    const globalStore = useGlobalStore.getState();
    globalStore.reset();
    
    const tabStore = useTabStore.getState();
    tabStore.reset();
    
    const routerStore = useRouterStore.getState();
    routerStore.reset();
    
    console.log('✅ All stores cleaned up successfully');
  } catch (error) {
    console.error('❌ Failed to cleanup stores:', error);
  }
};

// 开发工具
export const devTools = {
  // 获取所有store的状态
  getAllStates: () => ({
    global: useGlobalStore.getState(),
    tab: useTabStore.getState(),
    router: useRouterStore.getState(),
  }),
  
  // 重置所有stores
  resetAll: cleanupStores,
  
  // 分析性能
  analyzePerformance: () => {
    analyzeStorePerformance('global-store');
    analyzeStorePerformance('tab-store');
    analyzeStorePerformance('router-store');
  },
  
  // 健康检查
  healthCheck: () => {
    const results = {
      global: healthCheckStore(useGlobalStore, 'global-store'),
      tab: healthCheckStore(useTabStore, 'tab-store'),
      router: healthCheckStore(useRouterStore, 'router-store'),
    };
    
    console.group('🏥 Store Health Check');
    Object.entries(results).forEach(([name, result]) => {
      console.log(`${name}: ${result.isHealthy ? '✅ Healthy' : '❌ Issues found'}`);
      if (result.issues.length > 0) {
        console.log('Issues:', result.issues);
      }
      if (result.suggestions.length > 0) {
        console.log('Suggestions:', result.suggestions);
      }
    });
    console.groupEnd();
    
    return results;
  },
  
  // 导出状态
  exportStates: () => {
    const states = devTools.getAllStates();
    const blob = new Blob([JSON.stringify(states, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `codegraph-states-${new Date().toISOString()}.json`;
    a.click();
    URL.revokeObjectURL(url);
  },
  
  // 导入状态
  importStates: (file: File) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = (e) => {
        try {
          const states = JSON.parse(e.target?.result as string);
          
          // 导入状态到各个store
          if (states.global) {
            // 这里需要实现状态导入逻辑
            console.log('Importing global state:', states.global);
          }
          
          if (states.tab) {
            console.log('Importing tab state:', states.tab);
          }
          
          if (states.router) {
            console.log('Importing router state:', states.router);
          }
          
          resolve(states);
        } catch (error) {
          reject(error);
        }
      };
      reader.onerror = reject;
      reader.readAsText(file);
    });
  },
};

// 在开发环境下暴露到全局
if (process.env.NODE_ENV === 'development') {
  (window as any).storeDevTools = devTools;
  console.log('🛠️ Store dev tools available at window.storeDevTools');
}

// 默认导出
export default {
  initializeStores,
  cleanupStores,
  devTools,
};
